import { useStorage } from '@vueuse/core'
import { defineStore } from 'pinia'

export type LayoutMode = 'side' | 'top' | 'mix' | 'split' | 'double' | 'compact'
export type ThemeMode = 'light' | 'dark'

export interface ThemeSettings {
  primaryColor: string
  infoColor: string
  successColor: string
  warningColor: string
  errorColor: string
}

export interface LayoutState {
  mode: 'side' | 'top' | 'mix' | 'split' | 'double' | 'compact'
  theme: 'light' | 'dark'
  primaryColor: string
  collapsed: boolean
  showLogo: boolean
  showTags: boolean
  showBreadcrumb: boolean
  showCollapseButton: boolean
  showSearch: boolean
  topMenuMode: 'embed' | 'separate'
  siderPosition: 'left' | 'right'
  menuWidth: number
}

export const useLayoutStore = defineStore('layout', () => {
  const layout = useStorage<LayoutState>('layout-config', {
    mode: 'side',
    theme: 'light',
    primaryColor: '#1890ff',
    collapsed: false,
    showLogo: true,
    showTags: true,
    showBreadcrumb: true,
    showCollapseButton: true,
    showSearch: true,
    topMenuMode: 'embed',
    siderPosition: 'left',
    menuWidth: 180
  })

  // 切换主题
  function setTheme(theme: ThemeMode) {
    layout.value.theme = theme
    // 同步更新 HTML 的 class
    if (theme === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }

  // 切换布局模式
  function setMode(mode: LayoutMode) {
    layout.value.mode = mode
  }

  // 切换折叠状态
  function toggleCollapsed() {
    layout.value.collapsed = !layout.value.collapsed
  }

  // 设置显示标签页
  function setShowTags(show: boolean) {
    layout.value.showTags = show
  }

  // 设置显示面包屑
  function setShowBreadcrumb(show: boolean) {
    layout.value.showBreadcrumb = show
  }

  // 设置显示Logo
  function setShowLogo(show: boolean) {
    layout.value.showLogo = show
  }

  // 设置主题色
  function setPrimaryColor(color: string) {
    layout.value.primaryColor = color
  }

  // 设置侧边栏位置
  function setSiderPosition(position: 'left' | 'right') {
    layout.value.siderPosition = position
  }

  // 设置菜单宽度
  function setMenuWidth(width: number) {
    layout.value.menuWidth = width
    document.documentElement.style.setProperty('--menu-width', `${width}px`)
  }

  // 设置收缩按钮显示状态
  function setShowCollapseButton(show: boolean) {
    layout.value.showCollapseButton = show
  }

  // 设置搜索框显示状态
  function setShowSearch(show: boolean) {
    layout.value.showSearch = show
  }

  return {
    layout,
    setTheme,
    setMode,
    toggleCollapsed,
    setShowTags,
    setShowBreadcrumb,
    setShowLogo,
    setPrimaryColor,
    setSiderPosition,
    setMenuWidth,
    setShowCollapseButton,
    setShowSearch
  }
})
